package control

import "jvmgo/ch05/instructions/base"
import "jvmgo/ch05/rtda"

/*
tableswitch
<0-3 byte pad>
defaultbyte1
defaultbyte2
defaultbyte3
defaultbyte4
lowbyte1
lowbyte2
lowbyte3
lowbyte4
highbyte1
highbyte2
highbyte3
highbyte4
jump offsets...
*/

// Access jump table by index and jump
type TABLE_SWITCH struct {
    defaultOffset int32
    low           int32
    high          int32
    jumpOffsets   []int32
}

func (self *TABLE_SWITCH) FetchOperands(reader *base.BytecodeReader) {
    reader.SkipPadding()
    self.defaultOffset = reader.ReadInt32()
    self.low = reader.ReadInt32()
    self.high = reader.ReadInt32()
    //jumpOffsetsCount是case语句的个数
    jumpOffsetsCount := self.high - self.low + 1
    self.jumpOffsets = reader.ReadInt32s(jumpOffsetsCount)
}

func (self *TABLE_SWITCH) Execute(frame *rtda.Frame) {
    index := frame.OperandStack().PopInt()

    var offset int
    //如果偏移量在low和high之间，代表选中一个case语句
    if index >= self.low && index <= self.high {
        offset = int(self.jumpOffsets[index - self.low])
    } else {
        //范围不对就跳到默认偏移量
        offset = int(self.defaultOffset)
    }

    base.Branch(frame, offset)
}
